package com.service.impl;

import com.controller.WebSocketController;
import com.dto.CommentsWithUserDTO;
import com.event.NotificationEvent;
import com.mapper.CommentsMapper;
import com.mapper.NotesMapper;
import com.pojo.Comments;
import com.pojo.Notifications;
import com.pojo.Result;
import com.service.CommentsService;
import com.service.NotificationsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    private CommentsMapper commentsMapper;
    @Autowired
    private NotesMapper notesMapper;
    @Autowired
    private NotificationsService notificationsService;
    @Autowired
    private WebSocketController webSocketController;
    @Autowired
    private ApplicationEventPublisher publisher;


    @Override
    public Integer getUserIdByCommentId(Integer commentId) {
        if (commentId == null || commentId <= 0) {
            throw new IllegalArgumentException("无效的评论ID");
        }
        return commentsMapper.selectUserIdByCommentId(commentId);
    }

    @Override
    public Result<Comments> createComment(Comments comment) {
        try {
            LocalDateTime now = LocalDateTime.now();
            comment.setCreatedAt(now);
            comment.setUpdatedAt(now);

            if (comment.getParentId() == null || comment.getParentId() == 0) {
                comment.setParentId(null);
            }

            int result = commentsMapper.insert(comment);
            if (result <= 0) {
                return Result.error("创建评论失败");
            }

            if (comment.getParentId() == null) {
                // 评论笔记
                Integer noteAuthorId = notesMapper.selectAuthorIdByNoteId(comment.getNoteId());
                if (noteAuthorId != null && !noteAuthorId.equals(comment.getUserId())) {
                    Notifications notification = new Notifications();
                    notification.setUserId(noteAuthorId);
                    notification.setType("COMMENT");
                    notification.setSourceId(comment.getId());
                    notification.setTargetId(comment.getNoteId());
                    notification.setRead(false);
                    notification.setCreatedAt(now);

                    // 保存通知到数据库
                    notificationsService.createNotification(notification);

                    // 发布事件（解耦推送）
                    publisher.publishEvent(new NotificationEvent(notification));
                }
            } else {
                // 回复评论
                Integer parentCommentAuthorId = commentsMapper.selectUserIdByCommentId(comment.getParentId());
                if (parentCommentAuthorId != null && !parentCommentAuthorId.equals(comment.getUserId())) {
                    Notifications notification = new Notifications();
                    notification.setUserId(parentCommentAuthorId);
                    notification.setType("REPLY");
                    notification.setSourceId(comment.getId());
                    notification.setTargetId(comment.getNoteId());
                    notification.setRead(false);
                    notification.setCreatedAt(now);

                    // 保存通知到数据库
                    notificationsService.createNotification(notification);

                    // 发布事件（解耦推送）
                    publisher.publishEvent(new NotificationEvent(notification));
                }
            }

            return Result.success(comment);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> updateComment(Comments comment) {
        try {
            comment.setUpdatedAt(LocalDateTime.now());
            int result = commentsMapper.update(comment);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("更新评论失败");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> deleteComment(Integer id) {
        try {
            // 先删除所有回复
            commentsMapper.deleteByParentId(id);
            // 再删除评论本身
            int result = commentsMapper.delete(id);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error("删除评论失败");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Void> deleteCommentsByNoteId(Integer noteId) {
        try {
            // 删除所有回复
            commentsMapper.deleteRepliesByNoteId(noteId);
            // 删除所有评论
            int result = commentsMapper.deleteByNoteId(noteId);
            if (result >= 0) {
                return Result.success();
            } else {
                return Result.error("删除评论失败");
            }
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<CommentsWithUserDTO> getCommentById(Integer id) {
        try {
            // 获取评论基本信息
            Comments comment = commentsMapper.selectById(id);
            if (comment == null) {
                return Result.error("评论不存在");
            }

            // 转换为DTO并添加用户信息
            CommentsWithUserDTO dto = convertToDTO(comment);
            return Result.success(dto);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<CommentsWithUserDTO>> getCommentsTreeByNoteId(Integer noteId) {
        try {
            // 获取所有评论（包含用户信息）
            List<CommentsWithUserDTO> allComments = commentsMapper.selectCommentsWithUserByNoteId(noteId);

            // 构建评论树
            List<CommentsWithUserDTO> commentTree = buildCommentTree(allComments);
            return Result.success(commentTree);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    // 构建树形结构
    private List<CommentsWithUserDTO> buildCommentTree(List<CommentsWithUserDTO> comments) {
        // 按 parentId 分组（非顶级评论）
        Map<Integer, List<CommentsWithUserDTO>> commentMap = comments.stream()
                .filter(comment -> comment.getParentId() != null && comment.getParentId() != 0)
                .collect(Collectors.groupingBy(CommentsWithUserDTO::getParentId));

        // 设置子评论
        comments.forEach(comment -> {
            List<CommentsWithUserDTO> replies = commentMap.get(comment.getId());
            comment.setReplies(replies != null ? replies : Collections.emptyList());
        });

        // 返回顶级评论（parentId 为 null）
        return comments.stream()
                .filter(comment -> comment.getParentId() == null)
                .collect(Collectors.toList());
    }

    @Override
    public Result<List<Comments>> getCommentsByUserId(Integer userId) {
        try {
            List<Comments> comments = commentsMapper.selectByUserId(userId);
            return Result.success(comments);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<List<CommentsWithUserDTO>> getRepliesByParentId(Integer parentId) {
        try {
            List<CommentsWithUserDTO> replies = commentsMapper.selectRepliesWithUserByParentId(parentId);
            return Result.success(replies);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Integer> getCommentCountByNoteId(Integer noteId) {
        try {
            int count = commentsMapper.countByNoteId(noteId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    @Override
    public Result<Integer> getCommentCountByUserId(Integer userId) {
        try {
            int count = commentsMapper.countByUserId(userId);
            return Result.success(count);
        } catch (Exception e) {
            return Result.error(500, "服务器内部错误: " + e.getMessage());
        }
    }

    // 将Comments转换为CommentsWithUserDTO
    private CommentsWithUserDTO convertToDTO(Comments comment) {
        CommentsWithUserDTO dto = new CommentsWithUserDTO();
        dto.setId(comment.getId());
        dto.setUserId(comment.getUserId());
        dto.setNoteId(comment.getNoteId());
        dto.setContent(comment.getContent());
        dto.setParentId(comment.getParentId());
        dto.setCreatedAt(comment.getCreatedAt());
        dto.setUpdatedAt(comment.getUpdatedAt());

        dto.setNickname("用户" + comment.getUserId());
        dto.setAvatarUrl("/avatar/default.png");

        return dto;
    }
}